package com.oeandn.common.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lwl
 * @Date: 2022/08/12/13:59
 * @Description:
 */
public class DaysUtil {
    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
    *字符串的日期格式的计算
    */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600);

        return Integer.parseInt(String.valueOf(between_days));
    }


    /**
     *字符串的日期格式的计算
     * 优化，desc最好用常量来表达
     */
    public static String dayBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        //优化，如果else要return的话直接使用if中断
        if(StrUtil.isBlank(smdate) || StrUtil.isBlank(bdate)){
            return "-";
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        float time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        float time2 = cal.getTimeInMillis();
        float between_days=(time2-time1)/(1000*3600);
        DecimalFormat fnum = new DecimalFormat("##0.0");
        return fnum.format(between_days);
    }
}
